package com.kaifamiao.sync;

public class DepositTask implements Runnable {

    private Account account;
    private long amount;

    private DepositTask(Account account, long amount) {
        this.account = account;
        this.amount = amount;
    }

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        for ( int i = 0; i < 3; i++ ) {
            synchronized ( account ) { // enter monitor
                if (!account.enough) {
                    System.out.printf("%s开始存钱，当前余额为: %d\n", name, account.balance);
                    Thread.yield();
                    account.balance += amount; // 村款
                    account.enough = true; // 钱够了
                    Thread.yield();
                    System.out.printf("%s存钱结束，当前余额为: %d\n", name, account.balance);
                    continue;
                }
                System.out.printf("账上钱够用，%s不必存款\n", name);
            } // exit monitor
        }
    }

    public static void launch(String name, Account account, long amount) {
        Runnable runnable = new DepositTask( account, amount);
        Thread t = new Thread(runnable, name);
        t.start();
    }

}
